require 'rubygems'
require 'open-uri'
require 'hpricot'
require 'logger'
require_relative '../wine.class.rb'

class WineCc
	def self.getWines(ean)
		result = Array.new(0)


		baseUrl = "http://www.wein.cc"
		doc = Hpricot(open(baseUrl + "/wein/weinsuche.php?q=" + URI::encode(ean)))

		# Suche alle Links auf der Seite
		allLinks = (doc/"a")

		allLinks.each do |link|
			href = link.attributes['href']
			if href.include? "wein/produktansicht" 
				if !href.include? "#"
					href = baseUrl + href
					$log.debug("Now checking: " + href)
					weinDoc = Hpricot(open(href))
					allRows = (weinDoc/"//table[@class=\"attribute\"]/tr")
					wine = Wine.new
					wine.source = href
					
					nameOnPage = (weinDoc/"//h1[@itemprop=\"name\"]").inner_html
					parts = nameOnPage.lines(", ")
					#TODO check if all is there
					wine.name = parts.next[0..-3]
					wine.year = parts.next
					
					allRows.each do |row|
						rowString = row.to_s
						if rowString.include? "Produzent"
							tag = row.at("a")
							if tag
								wine.producer = tag.inner_html
							end
						end
						if rowString.include? "Land"
							tag = row.at("a")
							if tag
								wine.country = tag.inner_html
							end
						end
						if rowString.include? "Region"
							tag = row.at("a")
							if tag
								wine.region = tag.inner_html
							end
						end
						if rowString.include? "Gebiet"
							tag = row.at("a")
							if tag
								wine.area = tag.inner_html
							end
						end
						if rowString.include? "EAN"
							tag = row.at("a")
							if tag
								wine.ean = tag.inner_html
							end
						end
						if rowString.include? "Kategorie"
							tag = row.at("a")
							if tag
								wine.category = tag.inner_html
							end
						end
						if rowString.include? "Sorte"
							tag = row.at("a")
							if tag
								wine.type = tag.inner_html
							end
						end
						if rowString.include? "Alkohol"
							tag = row.at("td")
							if tag
								wine.alcohol = tag.inner_html
							end
						end
					end
					result << wine
					$log.debug(wine.to_s)
				end
			end
		end
		(result)
	end

end